//
//  HomeView.m
//  Village
//
//  Created by 程虎 on 2017/9/6.
//  Copyright © 2017年 程虎. All rights reserved.
//

#import "HomeView.h"
#import "YJSegmentedControl.h"
#import "HomeTableCell.h"
#import "SearchView.h"
#import "HomeHttpTools.h"
#import "TZGGHttpTools.h"
#import "PolicyHttpTools.h"
#import "PolicyModel.h"
#import "ShowEmptyView.h"
@interface HomeView ()<SDCycleScrollViewDelegate,YJSegmentedControlDelegate, UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) UIViewController *controllers;
@property (assign, nonatomic) CGFloat headViewHeight;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSArray *dataAry;
@property (strong, nonatomic) NSArray *bannerAry;
@property (strong, nonatomic) SearchView *searchs;
@property (strong, nonatomic) SDCycleScrollView *bannerScroll;
@property (strong, nonatomic) SDCycleScrollView *newsScroll;
@property (strong, nonatomic) UILabel *noticeLab;
@property (assign, nonatomic) NSInteger indexType;//0 村头条 1 政策法规
@end

@implementation HomeView

- (instancetype)initWithFrame:(CGRect)frame SuperView:(UIViewController *)controllers
{
    self = [super initWithFrame:frame];
    if (self) {
        self.controllers = controllers;
        self.backgroundColor = [UIColor whiteColor];
        
        self.headViewHeight = (204.0 / 375.0) * self.frame.size.width + 100 + 10 + 34 /*+ 45 */;
        self.indexType = 0;
        
        [self set_UI];
    }
    return self;
}


#pragma mark - 设置UI
- (void)set_UI
{
//    self.dataAry = [Globle getInstance].homeHeadlineArys;
    LSLog(@"home ----- %ld",[Globle getInstance].homeHeadlineArys.count);
    
    self.tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeTableCell" bundle:nil] forCellReuseIdentifier:@"HomeTableCell"];
    self.tableView.tableHeaderView = [self headView];
//    ShowEmptyView *emptyView = [[ShowEmptyView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H - self.headViewHeight - 55.5 - 49)];
//    emptyView.backgroundColor = [UIColor whiteColor];
//    self.tableView.tableFooterView = emptyView;
    
    
    
    
    
    [self addSubview:_tableView];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    //首页新闻
    [self getBanner];
    [self getData:self.indexType];
    
    WeakSelf(weakSelf);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf getData:self.indexType];
        
        [self getBanner];
//        [weakSelf getAnnucements];
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeLoginRefresh) name:RefreshLoginInfo object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:RefreshLoginInfo object:nil];
}

#pragma mark - 登录刷新
- (void)homeLoginRefresh
{
    self.tableView.tableHeaderView = [UIView new];
    self.tableView.tableHeaderView = [self headView];
    [self.tableView reloadData];
}

#pragma mark- UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeTableCell *cell = [HomeTableCell cellWithTableView:tableView];
    if (self.indexType == 0) {
        cell.model = self.dataAry[indexPath.row];
    }
    else {
        cell.model1 = self.dataAry[indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_delegate && [_delegate respondsToSelector:@selector(tableNewsClickWithData:WithIndex:)]) {
        [_delegate tableNewsClickWithData:self.dataAry[indexPath.row] WithIndex:self.indexType];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Class currentClass = [HomeTableCell class];
    return [self.tableView cellHeightForIndexPath:indexPath model:self.dataAry[indexPath.row] keyPath:self.indexType == 0 ? @"model" : @"model1" cellClass:currentClass contentViewWidth:[self cellContentViewWith]];
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 43.5;
//}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView *headerView = [UIView new];
//    headerView.backgroundColor = [UIColor whiteColor];
//
//    UILabel *lab = [[Tools shareInstance] creat_Label:@"头条新闻" Color:KRedColors Font:15 tag:-1 Alignment:0 Lines:1];
//
//    UIImageView *line = [UIImageView new];
//    line.backgroundColor = K_LineColor;
//    [headerView sd_addSubviews:@[lab,line]];
//
//    lab.sd_layout
//    .leftSpaceToView(headerView, 12)
//    .centerYEqualToView(headerView)
//    .widthIs(100)
//    .heightIs(20);
//
//    line.sd_layout
//    .leftSpaceToView(headerView, 10)
//    .bottomSpaceToView(headerView, 0)
//    .rightSpaceToView(headerView, 10)
//    .heightIs(0.5);
//
//    return headerView;
//}

- (void)segumentSelectionChange:(NSInteger)selection
{
    self.dataAry = [NSArray array];
    self.indexType = selection;
    [self getData:selection];
    [self.tableView reloadData];
}

- (CGFloat)cellContentViewWith
{
    //contentViewWidth  一定要计算cell的宽度  计算出来的高度 才是准确的
    CGFloat width = SCREEN_W ;
    
    // 适配ios7横屏
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}

#pragma mark - 数据请求

- (void)setAreaIDStr:(NSString *)areaIDStr
{
    _areaIDStr = areaIDStr;
    self.searchs.locationStr = [Globle getInstance].locations.City;
    if (![_areaIDStr isEqualToString: [Globle getInstance].areaid]) {
        [self getData:self.indexType];
    }
//    [self getAnnucements];
}

#pragma mark - 获取banner 数据
- (void)getBanner
{
    WeakSelf(weakSelf);
    [HomeHttpTools GetBannerSuccess:^(NSArray *valueAry,NSArray *imgArys,NSArray *titleArys) {
        [weakSelf.tableView.mj_header endRefreshing];
        self.bannerAry = valueAry;
        self.bannerScroll.imageURLStringsGroup = imgArys;
        self.bannerScroll.titlesGroup = titleArys;
//        [weakSelf.tableView reloadData];
    } failure:^(NSString *error) {
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - 获取头条数据
- (void)getData:(NSInteger )codes
{
    if (codes == 0) {
        [self getHealine];
    }
    else {
        [self getPolicy];
    }
}

#pragma mark - 获取村头条
- (void)getHealine
{
    WeakSelf(weakSelf);
    [MBProgressHUD showMessage:@"正在加载..." toView:self];
    [HomeHttpTools GetHeadlineSuccess:^(NSArray *valueAry) {
        [MBProgressHUD hideHUDForView:self];
        
        [weakSelf.tableView.mj_header endRefreshing];
//         [[Globle getInstance] saveHomeHeadline:[VillageModel mj_keyValuesArrayWithObjectArray:valueAry]];
        
        self.dataAry = [NSMutableArray arrayWithArray:valueAry];
        [EmptyFunction hideEmpty:self.tableView];
        [weakSelf.tableView reloadData];
    } failure:^(NSString *error) {
        [MBProgressHUD hideHUDForView:self];
        [MBProgressHUD showError:error toView:self];
        [EmptyFunction showEmpty:self.tableView Height:SCREEN_H - self.headViewHeight - 55.5 - 49];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - 获取政策法规
- (void)getPolicy
{
    WeakSelf(weakSelf);
    [PolicyHttpTools GetPolicyWithPageNum:1 Success:^(NSDictionary *valueDict) {
        [weakSelf.tableView.mj_header endRefreshing];
//        [[Globle getInstance] savePolicy:valueDict[@"list"]];
        self.dataAry = [PolicyModel mj_objectArrayWithKeyValuesArray:valueDict[@"list"]];
        [EmptyFunction hideEmpty:self.tableView];
        if (_indexType == 1){
            if ([Globle getInstance].account.userid.length > 0){
                if ([Globle getInstance].isNormal){
                    self.dataAry = nil;
                    [EmptyFunction showEmpty:self.tableView Height:SCREEN_H - self.headViewHeight - 55.5 - 49];
                }else{
                    
                }
            }else{
                self.dataAry = nil;
                [EmptyFunction showEmpty:self.tableView Height:SCREEN_H - self.headViewHeight - 55.5 - 49];
            }
          
        }
        [self.tableView reloadData];
    } failure:^(NSString *error) {
        [EmptyFunction showEmpty:self.tableView Height:SCREEN_H - self.headViewHeight - 55.5 - 49];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - 获取通知公告
- (void)getAnnucements
{
    WeakSelf(weakSelf);
    [TZGGHttpTools GetTZGGPageNum:1 Success:^(NSDictionary *valueDict) {
        [weakSelf.tableView.mj_header endRefreshing];
    } failure:^(NSString *error) {
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - tablview 头部内容
- (UIView *)headView {

    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.headViewHeight)];
    headView.backgroundColor = [Util colorWithHexString:@"#f7f7f7"];
    
    self.bannerScroll = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_W, self.headViewHeight - 100 - 10 - 34) delegate:self placeholderImage:[UIImage imageNamed:@"banner_default"]];
    self.bannerScroll.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    self.bannerScroll.currentPageDotImage = [UIImage imageNamed:@"pageContro_on"];
    self.bannerScroll.pageDotImage = [UIImage imageNamed:@"pageContro_off"];
    [headView addSubview:self.bannerScroll];
    
    self.searchs = [[SearchView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, kNavHeight) Type:0 ShowView:self.controllers];
    self.searchs.placeholderStr = @"搜索村落";
    self.searchs.searchBlock = ^(NSString *searchStr) {
        LSLog(@"search ------  %@",searchStr);
    };
    [headView addSubview:self.searchs];
    
    UIView *middleView = [self creatMiddleView];
    [headView addSubview:middleView];
    
//公告
//        UIView *bottomView = [self creatNoticeView];
//        [_headView addSubview:bottomView];
    
    middleView.sd_layout
    .leftSpaceToView(headView, 0)
    .topSpaceToView(self.bannerScroll, 0)
    .rightSpaceToView(headView, 0)
    .heightIs(100);
    
    //        bottomView.sd_layout
    //        .leftSpaceToView(headView, 0)
    //        .topSpaceToView(middleView, 10)
    //        .rightSpaceToView(headView, 0)
    //        .heightIs(45);
    //
    [middleView updateLayout];
    NSArray * btnDataSource3 = @[@"村头条", @"政策法规"];
    YJSegmentedControl * segment3 = [YJSegmentedControl segmentedControlFrame:CGRectMake(0, middleView.bottom + 10, self.bounds.size.width, 34) titleDataSource:btnDataSource3 backgroundColor:[UIColor whiteColor] titleColor:[Util colorWithHexString:@"#666666"] titleFont:[UIFont fontWithName:@".Helvetica Neue Interface" size:15.0f] selectColor:KRedColors buttonDownColor:KRedColors Delegate:self];
    [headView addSubview:segment3];
    
    UIImageView *line = [UIImageView new];
    line.backgroundColor = K_LineColor;
    [headView addSubview:line];
    
    line.sd_layout
    .leftSpaceToView(headView, 10)
    .bottomSpaceToView(headView, 0)
    .rightSpaceToView(headView, 10)
    .heightIs(0.5);
    
    return headView;
}

- (UIView *)creatMiddleView
{
    UIView *bkView = [UIView new];
    bkView.backgroundColor = [UIColor whiteColor];
    NSArray *dataAry = [NSArray array];
    if ([Globle getInstance].account.userid == nil) {//未登录、未注册、游客模式
        dataAry = @[@{@"title":@"村落查询",@"img":@"villageQuery_home"},@{},@{}];
    }
    else {
        if ([Globle getInstance].isNormal)
        {
            dataAry = @[@{@"title":@"村落查询",@"img":@"villageQuery_home"},@{},@{}];
        }
        else {
            dataAry = @[@{@"title":@"通知公告",@"img":@"inform"},
                        @{@"title":@"村落查询",@"img":@"villageQuery_home"},
                        @{@"title":@"我的村落",@"img":@"myVillage_home"}];
        }
    }
    NSMutableArray *temp = [NSMutableArray array];
    for (int i = 0; i < dataAry.count; i++) {
        NSDictionary *dict = dataAry[i];
        UIView *views = [self creat_view:dict[@"img"] titles:dict[@"title"] Tag:i];
        [bkView addSubview:views];
        [temp addObject:views];
        views.sd_layout.heightIs(100);
    }
    [bkView setupAutoWidthFlowItems:[temp copy] withPerRowItemsCount:dataAry.count verticalMargin:0 horizontalMargin:0 verticalEdgeInset:0 horizontalEdgeInset:0];
    
    return bkView;
}
- (UIView *)creatNoticeView
{
    UIView *views = [UIView new];
    views.backgroundColor = [UIColor whiteColor];
    
    UIImageView *notice_Img = [UIImageView new];
    notice_Img.image = [UIImage imageNamed:@"announcement_home"];
    
    UIImageView *line = [UIImageView new];
    line.backgroundColor = K_LineColor;
    
    UIImageView *arrow_Img = [UIImageView new];
    arrow_Img.image = [UIImage imageNamed:@"arrow_home"];
    
    self.newsScroll = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_W, 45) delegate:self placeholderImage:nil];
    self.newsScroll.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.newsScroll.onlyDisplayText = YES;
    self.newsScroll.titleLabelTextColor = K_TitlesColor;
    self.newsScroll.titleLabelTextFont = LRFont(15);
    self.newsScroll.titleLabelBackgroundColor = [UIColor whiteColor];
    
    NSMutableArray *titlesArray = [NSMutableArray new];
    [titlesArray addObject:@"纯文字上下滚动轮播"];
    [titlesArray addObject:@"纯文字上下滚动轮播 -- demo轮播图4"];
    [titlesArray addObject:@"纯轮播图4"];
    self.newsScroll.titlesGroup = [titlesArray copy];
    [self.newsScroll disableScrollGesture];
    
    [views sd_addSubviews:@[notice_Img,line,self.newsScroll,arrow_Img]];
    
    notice_Img.sd_layout
    .leftSpaceToView(views, 15)
    .centerYEqualToView(views)
    .widthIs(31)
    .heightIs(14.5);
    
    line.sd_layout
    .leftSpaceToView(notice_Img, 9.5)
    .topSpaceToView(views, 10)
    .bottomSpaceToView(views, 10)
    .widthIs(0.5);
    
    arrow_Img.sd_layout
    .rightSpaceToView(views, 15)
    .centerYEqualToView(views)
    .widthIs(7.5)
    .heightIs(14);
    
    self.newsScroll.sd_layout
    .leftSpaceToView(line, 8)
    .centerYEqualToView(views)
    .rightSpaceToView(arrow_Img, 22.5)
    .heightRatioToView(views, 0.8);
    
    return views;
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSInteger type;
    if (cycleScrollView == self.bannerScroll) {
        type = 0;
    }
    else {
        type = 1;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(scrollNewsClickWithIndex:WithData:)]) {
        [_delegate scrollNewsClickWithIndex:type WithData:self.bannerAry[index]];
    }

}

- (UIView *)creat_view:(NSString *)img titles:(NSString *)titles Tag:(NSInteger)tags
{
    UIView *backViews = [UIView new];
    
    UIImageView *images = [UIImageView new];
    images.image = [UIImage imageNamed:img];
    
    UILabel *lab = [[Tools shareInstance] creat_Label:titles Color:[Util colorWithHexString:@"#666666"] Font:13 tag:-1 Alignment:1 Lines:1];
    self.noticeLab = [[Tools shareInstance] creat_Label:@"99+" Color:[UIColor whiteColor] Font:13 tag:-1 Alignment:1 Lines:1];
    self.noticeLab.backgroundColor = KRedColors;
    LRViewRadius(self.noticeLab, 9, 0.1, [UIColor clearColor]);
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    btn.tag = tags;
    [btn addTarget:self action:@selector(itemsClick:) forControlEvents:UIControlEventTouchUpInside];
    [backViews sd_addSubviews:@[images,lab,btn]];
//    if (tags == 0) {
//        [images addSubview:self.noticeLab];
//    }
    
    CGFloat width = 50;
    CGFloat height = 50;
    CGFloat margin = 8.5;
    
    images.sd_layout
    .centerXEqualToView(backViews)
    .topSpaceToView(backViews, 15)
    .widthIs(width)
    .heightIs(height);
    
    lab.sd_layout
    .topSpaceToView(images, margin)
    .centerYEqualToView(images)
    .widthRatioToView(backViews, 1)
    .heightIs(11.5);
    
    self.noticeLab.sd_layout
    .leftSpaceToView(images, images.centerX + 10)
    .topEqualToView(images).offset(-4)
    .minWidthIs(20)
    .heightIs(18);
    
    [self.noticeLab setSingleLineAutoResizeWithMaxWidth:50];
    btn.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    return backViews;
}

- (void)itemsClick:(UIButton *)buttons
{
    if (_delegate && [_delegate respondsToSelector:@selector(middleItemsClickWithIndex:)]) {
        [_delegate middleItemsClickWithIndex:buttons.tag];
    }
}
@end
